//
//  MSViewController.m
//  OrderingMerchantsSide
//
//  Created by iOS on 2018/9/19.
//  Copyright © 2018年 mls. All rights reserved.
//

#import "MSViewController.h"

@interface MSViewController ()
<
MSNavigationBarDelegate,
UIGestureRecognizerDelegate
>

@property (nonatomic, assign) BOOL          isCanUseSideBack;  // 手势是否启动
@property (nonatomic, strong) MBProgressHUD *hud;

@end

@implementation MSViewController


+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
    MSViewController *vc = [super allocWithZone:zone];
    
    @weakify(vc);
    [[vc rac_signalForSelector:@selector(viewDidLoad)] subscribeNext:^(RACTuple * _Nullable x) {
       
        @strongify(vc);
        [vc ms_addSubviews];
        [vc ms_bindViewModel];
    }];
    
    return vc;
}

- (instancetype)initWithViewModel:(id<MSViewModelProtocol>)viewModel
{
    if (self = [super init])
    {
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = UIColor.whiteColor;
    if ([self respondsToSelector:@selector(setAutomaticallyAdjustsScrollViewInsets:)])
    {
        [self setAutomaticallyAdjustsScrollViewInsets:NO];
    }
    if (@available(iOS 13, *))
    {
        self.overrideUserInterfaceStyle = UIUserInterfaceStyleLight;
    }
    
    [self setupNavBar];
    //[self.view addSubview:subView]时，将自定义的导航栏移到最上层
    @weakify(self);
    [[self.view rac_signalForSelector:@selector(addSubview:)] subscribeNext:^(RACTuple * _Nullable x) {
        
        @strongify(self);
        [self.view bringSubviewToFront:self.navBar];
    }];
    
//    [self cancelSideBack];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self setNeedsStatusBarAppearanceUpdate];
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    self.navigationController.navigationBarHidden = YES;
//    [self cancelSideBack];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
//    [self startSideBack];
}


#pragma mark - 右滑返回

/** 关闭ios右滑返回 */
-(void)cancelSideBack
{
    self.isCanUseSideBack = NO;
 
    if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)])
    {
        self.navigationController.interactivePopGestureRecognizer.delegate = self;
    }
}
/** 开启ios右滑返回 */
- (void)startSideBack
{
    self.isCanUseSideBack = YES;
    
    if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)])
    {
        self.navigationController.interactivePopGestureRecognizer.delegate = nil;
    }
}


// 解决手势冲突
//- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
//{
//    // 输出点击的view的类名
//    MSLog(@"%@", NSStringFromClass([touch.view class]));
//    
//    // 若为UITableViewCellContentView（即点击了tableViewCell），则不截获Touch事件
//    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"] || [NSStringFromClass([touch.view class]) isEqualToString:@"UIPickerTableViewWrapperCell"])
//    {
//        return NO;
//    }
//    
//    return  YES;
//}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer*)gestureRecognizer
{
    if ([gestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]])
    {
        return self.isCanUseSideBack;
    }
    else
    {
        return YES;
    }
}


#pragma mark - MSNavigationBarDelegate
/** 返回上一页 */
- (void)popLastPage
{
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - 自定义导航栏

- (void)setupNavBar
{
    _navBar = [[MSNavigationBar alloc] initWithTitle:self.title
                                       hasBackButton:self.navigationController.viewControllers.count > 1];
    _navBar.delegate = self;
    if (self.navigationController.viewControllers.count > 1)
    {
        MSViewController *lastVC = self.navigationController.viewControllers[self.navigationController.viewControllers.count - 2];
        _navBar.leftTextLabel.text = ms_stringIsEmpty(lastVC.navBar.titleLabel.text) ? @"返回" : lastVC.navBar.titleLabel.text;
    }
    
    [self.view addSubview:_navBar];
    
    [_navBar mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.left.right.equalTo(self.view);
        make.height.mas_equalTo(MS_NAV_BAR_HEIGHT);
    }];
    
    RACChannelTo(self.navBar.titleLabel, text) = RACChannelTo(self, title);
}

// 解决在iOS 9 之后横屏时，状态栏会消失（解决方法：确保plist 中的【View controller-based status bar appearance】为YES，然后重写ViewController的 - (BOOL)prefersStatusBarHidden ，返回值是NO。）
- (BOOL)prefersStatusBarHidden
{
    return NO;
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleDefault;
}

#pragma mark - rotate
/*
// 如个别界面支持横屏，重写下面两个方法即可
// 设置设备不支持自动旋转。
- (BOOL)shouldAutorotate
{
    return NO;
}

// 默认支持竖屏
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

// 设置进入界面默认支持的方向
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationPortrait;
}
// 屏幕旋转
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
{
    [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {

        MSLog(@"转屏前调入");
    }
                                 completion:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {

        MSLog(@"转屏后调入");
    }];
}
 */


#pragma mark - call

- (void)callPhoneStr:(NSString*)phoneStr
{
    if (phoneStr.length >= 1)
    {
        NSString *str2 = [[UIDevice currentDevice] systemVersion];
        if ([str2 compare:@"10.2" options:NSNumericSearch] == NSOrderedDescending || [str2 compare:@"10.2" options:NSNumericSearch] == NSOrderedSame)
        {
            NSString* PhoneStr = [NSString stringWithFormat:@"telprompt://%@",phoneStr];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:PhoneStr]
                                               options:@{}
                                     completionHandler:^(BOOL success) {
                
                MSLog(@"phone success");
            }];
            
        }
        else
        {
            NSMutableString* str1 = [[NSMutableString alloc] initWithString:phoneStr];// 存在堆区，可变字符串
            if (phoneStr.length == 10)
            {
                [str1 insertString:@"-"atIndex:3];
                [str1 insertString:@"-"atIndex:7];
            }
            else
            {
                [str1 insertString:@"-"atIndex:3];
                [str1 insertString:@"-"atIndex:8];
            }
            NSString * str = [NSString stringWithFormat:@"是否拨打电话\n%@",str1];
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:str
                                                                           message:nil
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            // 设置popover指向的item
//            alert.popoverPresentationController.barButtonItem = self.navigationItem.leftBarButtonItem;
            // 添加按钮
            [alert addAction:[UIAlertAction actionWithTitle:@"呼叫"
                                                      style:UIAlertActionStyleDestructive
                                                    handler:^(UIAlertAction *action) {
                
                MSLog(@"点击了呼叫按钮10.2下");
                NSString* PhoneStr = [NSString stringWithFormat:@"tel://%@",phoneStr];
                if ([PhoneStr hasPrefix:@"sms:"] || [PhoneStr hasPrefix:@"tel:"])
                {
                    UIApplication * app = [UIApplication sharedApplication];
                    if ([app canOpenURL:[NSURL URLWithString:PhoneStr]])
                    {
                        [app openURL:[NSURL URLWithString:PhoneStr]
                             options:@{}
                   completionHandler:nil];
                    }
                }
            }]];
            [alert addAction:[UIAlertAction actionWithTitle:@"取消"
                                                      style:UIAlertActionStyleCancel
                                                    handler:^(UIAlertAction *action) {
                
                MSLog(@"点击了取消按钮");
            }]];
            [self presentViewController:alert animated:YES completion:nil];
        }
    }
    else
    {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"空号"
                                                                       message:nil
                                                                preferredStyle:UIAlertControllerStyleAlert];
        // 设置popover指向的item
//        alert.popoverPresentationController.barButtonItem = self.navigationItem.leftBarButtonItem;
        // 添加按钮
        [alert addAction:[UIAlertAction actionWithTitle:@"取消"
                                                  style:UIAlertActionStyleCancel
                                                handler:^(UIAlertAction *action) {
            
            MSLog(@"点击了取消按钮");
        }]];
        [self presentViewController:alert animated:YES completion:nil];
    }
}


#pragma mark - appDelegate

- (AppDelegate *)appDelegate
{
    if (!_appDelegate)
    {
        _appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    }
    
    return _appDelegate;
}


#pragma mark - hud

- (void)showHudWithMessage:(NSString *)message
                      mode:(MBProgressHUDMode)mode
                  autoHide:(BOOL)autoHide
{
    ms_dispatch_main_async_safe(^(){
        
        [self.hud hideAnimated:YES];
        self.hud = [[MBProgressHUD alloc] init];
        self.hud.label.numberOfLines = 0;
        self.hud.removeFromSuperViewOnHide = YES;
        
        [self.view addSubview:self.hud];
        
        [self.hud mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.center.equalTo(self.view);
            make.left.mas_greaterThanOrEqualTo(30 * MS_ADAPTATION_RATIO);
        }];
        
        self.hud.mode = mode;
        self.hud.label.text = message;
        [self.hud showAnimated:YES];
        if (autoHide)
        {
            [self.hud hideAnimated:YES
                        afterDelay:1.5];
        }
    });
}

- (void)hideHud
{
    ms_dispatch_main_async_safe(^(){
        
        [self.hud hideAnimated:YES];
    });
}


#pragma mark - RAC
/** 添加控件 */
- (void)ms_addSubviews {}

/** 绑定 */
- (void)ms_bindViewModel {}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
